package com.itehima.sh.consumer.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("consumer")
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    DiscoveryClient discoveryClient;

    @GetMapping("{id}")
    public Map queryById(@PathVariable("id") String id){
        //这里的客户端名字不区分大小获取实例"user-service"
        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
        ServiceInstance serviceInstance = instances.get(0);
        String host = serviceInstance.getHost();//获取主机
        int port = serviceInstance.getPort();//获取端口
        String url = serviceInstance.getUri().toString();//获取请求URL
        Map forObject = restTemplate.getForObject(url + "/user/" + id, Map.class);
        return forObject;

     /*//写死
        String url = "http://localhost:8081/user/"+username;
        *//*RestTemplate会向http://localhost:8081/user/itcast(itcast就是username也是id)地址发起请求，
        并且得到响应的JSON数据。然后会将JSON数据反序列化为Map类型。*//*
        Map userMap = restTemplate.getForObject(url, Map.class);
        System.out.println(userMap);*/
    }

}